package com.mdc.mansion.api.web.common.resolver;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.mdc.mansion.common.exception.BusinessException;
import com.mdc.mansion.common.response.Result;
import com.mdc.mansion.common.response.ResultCode;
import com.mdc.mansion.common.util.JSONUtil;

/**<p>com.mdc.mansion.api.web.common.resolver.SystemHandlerExceptionResolver</p>
 * <p>Title: SystemHandlerExceptionResolver</p>
 * <p>Copyright: Copyright © 2010-2014</p>
 * <p>Company: jumei</p>
 * @author xiang.liu
 * @version 1.0
 */
@Component("exceptionResolver")
public class SystemHandlerExceptionResolver implements HandlerExceptionResolver {
    /**(non-Javadoc)
    * @param request
    * @param response
    * @param handler
    * @param ex
    * @return
    * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
    */  
    	
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Result result = null;
        if (BusinessException.class.isAssignableFrom(ex.getClass())) { // 业务异常
            BusinessException bex = (BusinessException) ex;
            result = new Result(ResultCode.COMMON_EXCEPTION);
            String message = bex.getMessage();
            result.setDescription(message);
            try {
                result.setDescription(JSONObject.parseObject(message));
            }catch (Exception e){}
        }else{// 系统异常
            result = new Result(ResultCode.COMMON_EXCEPTION);
            result.setDescription("system error!");
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            StringBuffer responseSb = new StringBuffer();
            responseSb.append(JSONUtil.getInstance().writeValueAsString(result));
            response.getWriter().println(responseSb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }

}
